package middlewares

import (
	"encoding/base64"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func Authorize() gin.HandlerFunc {
	return func(c *gin.Context) {

		if c.FullPath()=="/resource/*filepath" {
			return
		}
		token:=  c.GetHeader("Authorization")
		if token=="" {
			token=c.Query("token")
		}
		if token=="" {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
			return
		}
		data,err:=base64.StdEncoding.DecodeString(token)
		if err!=nil {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
			return
		}
		str,err:=decrypt(data)
		if err!=nil {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
			return
		}
		obj:=make(map[string]interface{})
		_ = json.Unmarshal([]byte(str), &obj)
		uid:=obj["uid"].(float64)
		if obj["file_name"]==nil{
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "访问未授权"})
			return
		}
		//file_name:=obj["file_name"].(string)
		expire:=int64(obj["expire"].(float64))


		if time.Now().Unix()>expire {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{"message": "token 过期"})
			return
		}

		// 记录上传文件次数
		if c.Request.URL.Path == "/upload/chunk" {
			chunk := c.Request.FormValue("chunk")
			chunkI, _ := strconv.Atoi(chunk)
			if chunkI==0{
				// 记录
			}
		}else{
			// 记录
		}

		c.Set("uid",uid)
		// 验证不通过，不再调用后续的函数处理
		//c.Abort()
		// return可省略, 只要前面执行Abort()就可以让后面的handler函数不再执行
	}
}
func decrypt(data []byte) (str string, err error) {
	//key := []byte("YzfNCQoF9P7tjwyZ")
	//if err != nil {
	//	return
	//}
	//str = string(dst)
	return
}
